package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ControlProblemFindingMapper;
import com.bf.electroplating.mapper.ControlProblemRectificationMapper;
import com.bf.electroplating.pojo.dto.problem.ControlProblemFindingQueryDTO;
import com.bf.electroplating.pojo.dto.problem.ControlProblemRectificationDTO;
import com.bf.electroplating.pojo.entity.ControlProblemFinding;
import com.bf.electroplating.pojo.entity.ControlProblemRectification;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.RectificationStatusEnum;
import com.bf.electroplating.pojo.vo.problem.ControlProblemFindingVO;
import com.bf.electroplating.pojo.vo.problem.ControlProblemRectificationVO;
import com.bf.electroplating.service.ControlProblemFindingService;
import com.bf.electroplating.service.ControlProblemRectificationService;
import com.bf.electroplating.service.PubAttachmentService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 15451
 * @description 针对表【control_problem_rectification】的数据库操作Service实现
 * @createDate 2025-06-26 10:01:24
 */
@Service
public class ControlProblemRectificationServiceImpl extends ServiceImpl<ControlProblemRectificationMapper, ControlProblemRectification>
        implements ControlProblemRectificationService {

    @Resource
    private ControlProblemFindingService containmentService;
    @Resource
    private PubAttachmentService attachmentService;
    @Resource
    private ControlProblemFindingMapper findingMapper;

    @Override
    public Page<ControlProblemFindingVO> pageList(ControlProblemFindingQueryDTO dto) {
        Page<ControlProblemFindingVO> page = containmentService.page(dto);
        page.getRecords().forEach(item -> {
            List<ControlProblemRectification> list = list(new LambdaQueryWrapper<ControlProblemRectification>().eq(ControlProblemRectification::getPId, item.getId())
                    .orderByDesc(ControlProblemRectification::getRectificationTime));
            if (!CollectionUtils.isEmpty(list)) {
                item.setRectificationTime(getDateStr(list.get(0).getRectificationTime()));
                item.setRectificationDescription(list.get(0).getRectificationDescription());
                item.setRectificationPhotoList(attachmentService.getWholeFile(list.get(0).getId(), AttModuleEnums.PROBLEM_RECTIFICATION_PHOTO.getCode()));
            }
        });
        return page;
    }

    @Override
    public ControlProblemRectificationVO detail(String id) {
        ControlProblemFindingVO vo = containmentService.detail(id);
        ControlProblemRectificationVO rectificationVO = new ControlProblemRectificationVO();
        BeanUtils.copyProperties(vo, rectificationVO);
        List<ControlProblemRectificationDTO> list = new ArrayList<>();
        List<ControlProblemRectification> rects = list(new LambdaQueryWrapper<ControlProblemRectification>()
                .eq(ControlProblemRectification::getPId, id).orderByDesc(ControlProblemRectification::getRectificationTime));
        rects.forEach(item -> {
            ControlProblemRectificationDTO rectificationDTO = new ControlProblemRectificationDTO();
            BeanUtils.copyProperties(item, rectificationDTO);
            rectificationDTO.setRectificationTime(getDateStr(item.getRectificationTime()));
            rectificationDTO.setRectificationPhotoList(attachmentService.getWholeFile(item.getId(), AttModuleEnums.PROBLEM_RECTIFICATION_PHOTO.getCode()));
            list.add(rectificationDTO);
        });
        rectificationVO.setRectificationList(list);
        return rectificationVO;
    }

    @Override
    public void rectification(ControlProblemRectificationDTO dto) {
        ControlProblemRectification entity = new ControlProblemRectification();
        BeanUtils.copyProperties(dto, entity);
        entity.setPId(dto.getPid());
        // 转换时间格式
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            entity.setRectificationTime(sdf.parse(dto.getRectificationTime()));
        } catch (ParseException e) {
            log.error("日期解析失败：" + e.getMessage());
            throw new RuntimeException("日期格式错误");
        }
        ControlProblemFinding candidate = findingMapper.selectById(dto.getPid());
        if (isNotSameDay(candidate.getPlanCompletionTime(),entity.getRectificationTime()) && candidate.getPlanCompletionTime().before(entity.getRectificationTime())){
            candidate.setRectificationStatus(RectificationStatusEnum.YET_OVER.getCode());
        }else {
            candidate.setRectificationStatus(RectificationStatusEnum.YET.getCode());
        }
        containmentService.updateById(candidate);
        save(entity);
        if (dto.getRectificationPhotoList() != null && !dto.getRectificationPhotoList().isEmpty()) {
            attachmentService.saveWholeAttachmentRel(dto.getRectificationPhotoList(), entity.getId(), AttModuleEnums.PROBLEM_RECTIFICATION_PHOTO.getCode());
        }
    }

    private boolean isNotSameDay(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);

        return cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR) ||
                cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH) ||
                cal1.get(Calendar.DAY_OF_MONTH) != cal2.get(Calendar.DAY_OF_MONTH);
    }

    private String getDateStr(Date date) {
        if (date == null) {
            return null;
        }
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return formatter.format(localDate);
    }
}




